package com.romejiang;

import org.apache.tomcat.jni.OS;

import java.net.InetAddress;
import java.net.NetworkInterface;

public class SystemMacAddress {
    /**
     * Method for get System Mac Address
     *
     * @return MAC Address
     */
    public static String getSystemMac() {
        String OSName = System.getProperty("os.name");
        System.out.println(OSName);
        if (OSName.contains("Windows")) {
            return (getMAC4Windows());
        } else {
            String[] ethers = new String[]{"eth0", "en0", "eth1", "en1", "eth2", "en2", "usb1",};
            for (int x = 0; x < ethers.length; x++) {
                String mac = getMAC4Linux(ethers[x]);
                if (mac != null) {
                    return mac;
                }
            }
            return null;
        }
    }

    /**
     * Method for get MAc of Linux Machine
     *
     * @param name
     * @return
     */
    private static String getMAC4Linux(String name) {
        try {
            NetworkInterface network = NetworkInterface.getByName(name);
            byte[] mac = network.getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            return (sb.toString());
        } catch (Exception E) {
            System.err.println("MAC address not found : " + name);
            return null;
        }
    }

    /**
     * Method for get Mac Address of Windows Machine
     *
     * @return
     */
    private static String getMAC4Windows() {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(addr);

            byte[] mac = network.getHardwareAddress();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }

            return sb.toString();
        } catch (Exception E) {
            System.err.println("System Windows MAC Exp : " + E.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        String macAddress = getSystemMac();
        System.out.println("System Mac Address : " + macAddress);
    }
}
